// 组合式函数
import { ref } from 'vue'
import * as _ from 'lodash'

export const loadingText = ref('');
export const loadingTextSigin = ref(false);
export const conversation_id = ref('')

// 处理流式响应
export const processStreamResponse = async(response: Response) => {
  loadingText.value = '';
  loadingTextSigin.value = false
  const reader = response.body?.getReader()
  const decoder = new TextDecoder()
  let buffer = ''

  if (reader) {
    let isReading = true
    while (isReading) {
      const { value, done } = await reader.read()
      if (done) {
        isReading = false
        break
      }
      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop() || ''

      for (const line of lines) {
        if (line) {
          let json: any = {}

          try {
            // 尝试解析 JSON，支持不同的前缀格式
            if (line.startsWith('data:data:')) {
              json = JSON.parse(line.substring(10))
            } else if (line.startsWith('data: ')) {
              json = JSON.parse(line.substring(6))
            } else if (line.startsWith('data:')) {
              json = JSON.parse(line.substring(5))
            } else {
              json = JSON.parse(line)
            }
          } catch (error) {
            // 解析失败，跳过这一行
            continue
          }
          const eventType = json['event']
          if(json.conversation_id){
            conversation_id.value = json.conversation_id;
          }

          // 处理 message 事件，获取报表内容
          if (eventType === 'message') {
            const answer = _.get(json, 'answer')
            console.log(json);
            console.log(answer);
            loadingText.value += answer
            console.log(loadingText.value);
          }
          if (eventType === 'message_end') {
            loadingTextSigin.value = true;
            console.log(loadingTextSigin.value);
          }
        }
      }
    }
  }
}
